package com.jiuxian.scheduling.listener.init;

import com.jiuxian.scheduling.commons.SpringApplicationContext;
import com.jiuxian.scheduling.dao.LogDao;
import com.jiuxian.scheduling.listener.zk.ZkDataListener;
import com.jiuxian.scheduling.tasks.SchedulerApplication;
import com.jiuxian.scheduling.util.SiteUtil;
import com.jiuxian.scheduling.util.ZKClientUtil;
import com.jiuxian.scheduling.vo.SchedingVO;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

import java.util.Date;
import java.util.List;

/**
 * Created by wangjingqing on 2017/12/18.
 * 初始化任务节点<br/>
 */
public class InitApplicationListener implements ApplicationListener<ContextRefreshedEvent> {
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        if(event.getApplicationContext().getParent() == null){
            List<String> nodes = ZKClientUtil.getNodes();
            if(CollectionUtils.isNotEmpty(nodes)){
                nodes.forEach(info->{
                    SchedingVO data = (SchedingVO)ZKClientUtil.getData(info);
                    if(data != null && data.getState() == 0){
                        System.out.println("初始化："+data.getName()+"=="+ SiteUtil.convertDate(data.getNextDate(),SiteUtil.FORMAT_SECOND));
                        Date nextDate = data.getNextDate() == null ? SiteUtil.getDate(new Date(),10):  data.getNextDate().compareTo(new Date()) < 1? SiteUtil.getDate(new Date(),10): SiteUtil.getDate(data.getNextDate(),10);
                        data.setNextDate(nextDate);
                        SchedulerApplication.addJob(data);
                        //初始化监听事件
                        ZKClientUtil.addDataListener(data.getName(),new ZkDataListener());
                    }
                });

            }
        }

        LogDao logDao = SpringApplicationContext.getClass(LogDao.class);
        if(!logDao.isExistTable("TASK_LOG")){
            logDao.createLogTable();
        }
    }
}
